package com.moyun.modelclass.fragment;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.moyun.modelclass.activity.ChatDetailActivity;
import com.moyun.modelclass.activity.ChatFavouriteActivity;
import com.moyun.modelclass.base.BaseFragment;
import com.moyun.modelclass.frank.BaseAdapter;
import com.moyun.modelclass.frank.HeartBeatRequest;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.api.ChatListApi;
import com.moyun.modelclass.http.api.ChatRemoveApi;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.R;
import com.moyun.modelclass.databinding.ItemChatBinding;
import com.moyun.modelclass.utils.DataUtil;
import com.moyun.modelclass.utils.StatusBarUtil;
import com.moyun.modelclass.view.recyclerview.DividerItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Meteor
 * 日期：2022/1/19 23:25
 * tip：消息
 */
public class MainChatFragment extends BaseFragment {
    private ImageView employmentHallBack;
    private RecyclerView employmentHallRecycler;

    private FrameLayout mLlMainHomeTop;
    private SmartRefreshLayout mainHomeFindRefresh;
    private BaseAdapter<ItemChatBinding, ChatListApi.ChatBean> adapter;


    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_main_chat;
    }

    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.d(TAG, "setUserVisibleHint() called with: isVisibleToUser = [" + isVisibleToUser + "]");
        if (isVisibleToUser) {
            homeFindData(true);
        }
    }
    @Override
    protected void assignViews(View view) {
        initView(view);
        employmentHallBack = (ImageView) view.findViewById(R.id.employment_hall_back);
        employmentHallRecycler = (RecyclerView) view.findViewById(R.id.main_home_find_recycler);
        mainHomeFindRefresh = (SmartRefreshLayout) view.findViewById(R.id.main_home_find_refresh);
        employmentHallRecycler.setLayoutManager(new LinearLayoutManager(mContext));
        employmentHallRecycler.addItemDecoration(new DividerItemDecoration(mContext, Color.parseColor("#EEEFEF"), 1, SizeUtils.dp2px(65), SizeUtils.dp2px(15)));
        StatusBarUtil.setPaddingSmart(requireActivity(), mLlMainHomeTop);
        adapter = new BaseAdapter<ItemChatBinding, ChatListApi.ChatBean>() {
            @Override
            protected void onBindData(ChatListApi.ChatBean bean, ItemChatBinding binding, int position, View itemView) {
                super.onBindData(bean, binding, position, itemView);
                binding.lastTime.setText(DataUtil.getTimeShowString(TimeUtils.string2Millis(bean.lastTime), false));
                if (bean.unReadCount == 0) {
                    binding.unReadCount.setVisibility(View.INVISIBLE);
                } else {
                    binding.unReadCount.setVisibility(View.VISIBLE);
                }
                if (!TextUtils.isEmpty(bean.lastChat) && bean.lastChat.contains("image/")) {
                    binding.msg.setText("图片");
                } else {
                    binding.msg.setText(bean.lastChat);
                }
                binding.item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ChatDetailActivity.start(mActivity, bean.receiveUserId);
                    }
                });
                binding.delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        remove(bean);
                    }
                });
                Glide.with(getContext())
                        .asBitmap()
                        .load(CommonConfiguration.splitResUrl(3, bean.toUser.avatar))
                        .placeholder(R.drawable.icon_head_portrait)
                        .error(R.drawable.icon_head_portrait)
                        .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                        .into(new BitmapImageViewTarget(binding.image) {
                            @Override
                            protected void setResource(Bitmap resource) {
                                super.setResource(resource);
                                binding.image.setImageBitmap(ImageUtils.toRound(resource));
                            }
                        });
            }
        };
        employmentHallRecycler.setAdapter(adapter);
    }
//    @Override
//    public void onHiddenChanged(boolean hidden) {
//        super.onHiddenChanged(hidden);
//        Log.d(TAG, "onHiddenChanged() called with: hidden = [" + hidden + "]");
//        if (!hidden) {
//            homeFindData(true);
//        }
//    }

    private void remove(ChatListApi.ChatBean bean) {
        EasyHttp.post(this)
                .api(new ChatRemoveApi(bean.receiveUserId))
                .request(new HttpCallback<HttpData<ChatRemoveApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<ChatRemoveApi.Bean> result) {
                        adapter.getData().remove(bean);
                        adapter.notifyDataSetChanged();
                    }
                });
    }

    @Override
    protected void registerListeners() {
        ClickUtils.applySingleDebouncing(employmentHallBack, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChatFavouriteActivity.start(requireActivity());
            }
        });
        mainHomeFindRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mLastId = "";
                homeFindData(true);
            }
        });
        mainHomeFindRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                homeFindData(false);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWechatPayEvent(List<HeartBeatRequest.NewChat> event) {
        // TODO: 2024/5/29
        List<ChatListApi.ChatBean> data = adapter.getData();
        int count = 0;
        boolean needNotify = false;
        for (HeartBeatRequest.NewChat newChat : event) {
            boolean find = false;
            for (ChatListApi.ChatBean datum : data) {
                if (newChat.userId.equals(datum.receiveUserId)) {
                    find = true;
                    if (datum.unReadCount != newChat.unreadCount) {
                        count++;
                    }
                    break;
                }
            }
            if (!find) {
                count++;
            }
        }
        if (count == 0) {
        } else {
            mLastId = "";
            homeFindData(true);
        }
    }
    private static final String TAG = "MainChatFragment";

    private void homeFindData(boolean isRefresh) {
        if (!CommonConfiguration.isLogin(kv)) {
            return;
        }
        mLastId = isRefresh ? "" : mLastId;
        EasyHttp.post(this)
                .api(new ChatListApi().setLastId(mLastId).setPageSize(100))
                .request(new HttpCallback<HttpData<ChatListApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<ChatListApi.Bean> result) {
                        Log.d(TAG, "onSucceed() called with: result = [" + result.getMessage() + "]");
                        mainHomeFindRefresh.finishRefresh();
                        mainHomeFindRefresh.finishLoadMore();
                        if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                            mLastId = result.getData().getList().get(result.getData().getList().size() - 1).id + "";
                            if (isRefresh) {
                                adapter.setData(result.getData().getList());
                            } else {
                                adapter.addData(result.getData().getList());
                            }
                        } else {
                            if (isRefresh) {
                                adapter.setData(new ArrayList<>());
                            }
                        }
                    }
                });
    }

    @Override
    protected void getExtras(Bundle bundle) {

    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume() called");
        homeFindData(true);
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void doAction() {

    }

    private String mLastId = "";


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void initView(View view) {
        mLlMainHomeTop = (FrameLayout) view.findViewById(R.id.ll_main_home_top);
    }
}
